package com.mj.listen3.链表;

import java.util.HashMap;

/**
 * https://leetcode-cn.com/problems/copy-list-with-random-pointer/
 */
public class _138_复制带随机指针的链表 {

    /**
     * 不使用额外空间
     *
     * @param head
     * @return
     */
    public Node copyRandomList(Node head) {
        if (head == null) return head;


        // 1、原始节点和副本节点串联 1->1'->2->2'->3->3'->null
        Node cur = head;
        Node next = null;

        while (cur != null) {
            next = cur.next;
            Node copy = new Node(cur.val);
            cur.next = copy;
            copy.next = next;
            cur = next;
        }

        // 2、设置所有拷贝节点的random节点
        cur = head;
        Node curCopy = null;
        while (cur != null) {
            next = cur.next.next;
            curCopy = cur.next;
            // 副本的random指针
            curCopy.random = cur.random == null ? null : cur.random.next;
            cur = next;
        }

        // 分割链表
        cur = head;
        Node res = cur.next;
        while (cur != null) {
            next = cur.next.next;
            curCopy = cur.next;
            cur.next = next;
            curCopy.next = next != null ? next.next : null;
            cur = next;
        }

        // 返回head'
        return res;
    }


    /**
     * 使用额外空间o(n)
     * <p>
     * 1 1'
     * 1'.next = get(1.next)
     * 1'.rand = get(1.rand)
     *
     * @param head
     * @return
     */
    public Node copyRandomList2(Node head) {
        if (head == null) return head;
        HashMap<Node, Node> hashMap = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            // 把所有节点的副本放置到map  node -> node'
            hashMap.put(cur, new Node(cur.val));
            cur = cur.next;
        }

        // 连接
        cur = head;
        while (cur != null) {
            // 连接next
            hashMap.get(cur).next = hashMap.get(cur.next);
            // 连接random
            hashMap.get(cur).random = hashMap.get(cur.random);
            cur = cur.next;
        }

        // 返回head'
        return hashMap.get(head);
    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}
